<?php
/**
 * RedCross Application
 *
 * @copyright Copyright (c) 2010, Kristian Stokke Tryggestad, Rune Vikestad, Andreas Flaten Wist, Simen Nicolai Echholt, Ole Henrik Jahren
 */


class Core_IndexController extends Zend_Controller_Action
{
    private $_shiftExchangeService;
    private $_userService;
    private $_courseService;

    public function init() {
        $this->_shiftExchangeService = RedCross_Factory::getService('Core_Service_ShiftExchange');
        $this->_userService = RedCross_Factory::getService('Core_Service_User');
        $this->_courseService = RedCross_Factory::getService('Core_Service_Course');
        $this->_shiftService = RedCross_Factory::getService('Core_Service_Shift');
        $this->_authService = RedCross_Factory::getService('Core_Service_Auth');
        $this->_eventService = RedCross_Factory::getService('Core_Service_Event');
    }

    public function indexAction() {
        $identity = $this->_authService->getIdentity();

        if (is_null($identity)) {
            // Not logged in. Redirect to login screen
            $this->_helper->redirector('login', 'user');
        }

        $memberId = $identity->member_id;

        if ($this->_helper->acl()->isAllowed('service:shiftRole', 'replaceRole', false)) {
            // TODO: If user isn't an admin, check shift leader status and fetch 
            // relevant shift exchange requests
            $shiftExchanges = $this->_shiftExchangeService->fetchAllUnhandled();
            $this->view->shiftExchanges = $shiftExchanges;
        }

        if ($this->_helper->acl()->isAllowed('service:user', 'confirm', false)) {
            $unconfirmedUsers = $this->_userService->fetchUsersOnlyUnconfirmed();
            $this->view->unconfirmedUsers = $unconfirmedUsers; 
        }

        $todaysDate = new RedCross_Date();
        $todaysDate->set(0, Zend_Date::MINUTE);
        $todaysDate->set(0, Zend_Date::HOUR);
        $todaysDate->set(0, Zend_Date::SECOND);
        $this->view->today = $todaysDate;

        $endOfWeek = clone $todaysDate;
        $endOfWeek->add(6, Zend_Date::DAY);
        $endOfWeek->set(23, Zend_Date::HOUR);
        $endOfWeek->set(59, Zend_Date::MINUTE);
        $endOfWeek->set(59, Zend_Date::SECOND);
        $this->view->endOfWeek = $endOfWeek;

        $this->view->events = $this->_eventService->fetchEventsThisWeek($todaysDate, $endOfWeek);
        $this->view->futureShifts = $this->_shiftService->fetchFutureShifts(null, null, $memberId);
        $this->view->unconfirmedShifts = $this->_shiftService->fetchAllUnconfirmedForMember($memberId);
        $this->view->missingshiftreports = $this->_shiftService->fetchAllMissingShiftReportsForMember($memberId);
        $this->view->expiringCourses = $this->_courseService->fetchAllExpiringCoursesForMember($memberId);
    }

}
